package org.chipu.jnids.alert;

import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

public final class SnortParser {
	private final static Map<Short, SnortComponentGenerator> snortEngines = new HashMap<Short, SnortComponentGenerator>();
	static {
		snortEngines.put((short) 1, new PrimaryDetectionEngine());
		snortEngines.put((short) 122, new PortScanDetectionEngine());
	}

	public static SnortEvent parseSyslogLine(String line) throws ParseException, UnknownHostException {
		if (line == null)
			return null;
		line = line.trim();
		if ("".equals(line))
			return null;
		SnortComponentGenerator engine = null;
		try {
			engine = getEngine(getGeneratorId(line));
		} catch(Exception ex) {
			throw new ParseException("Could not find the generator id (" + ex + ")\n\t" + line, 1);
		}
		return engine.parseSyslogLine(line);
	}

	private static short getGeneratorId(String line) {
		int i = line.indexOf('[');
		String sid = line.substring(i + 1, line.indexOf(']', i));
		return Short.parseShort(sid.split(":")[0]);
	}

	public static SnortComponentGenerator getEngine(short generatorid) {
		SnortComponentGenerator engine = snortEngines.get(generatorid);
		if (engine == null)
			engine = snortEngines.get((short) 1);
		return engine;
	}
}